//
// Created by cube on 2020/8/23.
//

#include "EventSystem.h"
#include "Events.h"

using namespace Lib;

void EventLoop::sendEvent(Event* event) {Loop::sendEvent(event);}

void EventLoop::sendEvent(const std::chrono::microseconds &millis, Event* event)
{if(!filter(event))__timeout_event_queue.lock()->send(millis,event);}

void EventLoop::work() {
    Event* event_p = nullptr;
    while (__timeout_event_queue.lock()->exec_one(event_p))EventLoop::action(event_p);
    Loop::work();
}

bool EventLoop::filter(Event*& event) {
    std::size_t index = 0;
    EventAgent agent(event);
    EventHandler* handler = nullptr;
    while (__handlers.ergodic_at(index++,handler) && !agent.__resend){
        if(handler->shieldEvent())continue;
        if(handler->onFilter(agent))return true;
    }
    return false;
}

void EventLoop::action(Event*& event) {
    std::size_t index = 0;
    EventAgent agent(event);
    EventHandler* handler = nullptr;
    while (__handlers.ergodic_at(index++,handler) && !agent.__resend){
        if(handler->shieldEvent())continue;
        handler->onEvent(agent);
    }
    if(!agent.__resend){
        event->event();
        delete event;
    }
}

void EventLoop::init() {sendEvent(new StartEvent());}
void EventLoop::exit() {sendEvent(new StopEvent(this));}

//Events

void StopEvent::event() { loop->quit(); }